 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Lib
 * Package  : net.solosky.easyavatar.api.impl
 * File     : AbstractProvider.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2011-10-24
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.api.impl;

import java.io.IOException;

import net.solosky.easyavatar.api.ApiException;
import net.solosky.easyavatar.api.ErrorCode;
import net.solosky.easyavatar.api.WebFriendProvider;
import net.solosky.easyavatar.api.http.HttpClient;
import net.solosky.easyavatar.api.http.HttpRequest;
import net.solosky.easyavatar.api.http.HttpResponse;

/**
 * 
 * 抽象的FriendProvider,提供了HttpClient的相关方法
 * 
 * @author solosky <solosky772@qq.com>
 *
 */
public abstract class AbstractWebFriendProvider implements WebFriendProvider{
	/**HTTP客户端对象*/
	private HttpClient client;
	
	public AbstractWebFriendProvider(){
		client = new HttpClient();
	}
	
	
	protected HttpClient getHttpClient(){
		return client;
	}
	
	protected HttpRequest createHttpRequest(String url, String method) {
		HttpRequest request = new HttpRequest(url, method);
		request.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 (.NET CLR 3.5.30729)");
		request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml,image/png,image/*;q=0.9,*/*;q=0.8");
		request.addHeader("Accept-Language", "en-us,en;q=0.5");
		request.addHeader("Accept-Encoding", "gzip,deflate");
		request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		return request;
	}
	
	protected HttpResponse executeHttpRequest(HttpRequest request) throws IOException{
		return client.execute(request);
	}
	
	protected void validateResponse(HttpResponse res) throws ApiException{
		if(res.getResponseCode()!=HttpResponse.HTTP_OK){
			throw new ApiException(ErrorCode.INVALID_RESPONSE);
		}
	}
}
